class Solution {
public:
    int trap(vector<int>& height) {
        if(!height.size())return 0;
        int n = height.size();
        vector<int> left(n), right(n);
        right[n - 1] = height[n - 1];
        left[0] = height[0]; 
        for(int i = 1; i < n; i++){
            if(left[i - 1] >= height[i])left[i] = left[i - 1];
            else left[i] = height[i];
        }
        for(int i = n - 2; i >= 0; i--){
            if(right[i + 1] >= height[i])right[i] = right[i + 1];
            else right[i] = height[i];
        }

        int ans = 0;
        for(int i = 1; i < n - 1; i++){
            ans += min(left[i], right[i]) - height[i];
        }
        return ans;
    }
};

//2021.4.2
 
